const defaultOptions = {
  timeout: 15000,
  dataType: 'json',
  header: {
    'content-type': 'application/json',
  },
};
const TOKEN_KEY = 'token';
const BASE_URL = 'https://api-hmugo-web.itheima.net/api';
const LOGIN_INVALID_CODE_LIST = ['INVALID_TOKEN', 'EXPIRED_TOKEN'];
const SUCCESS = 'SUCCESS';
const LOADING_DELAY = 50; // 50ms 延迟
let loadingTimer;

const handleURL = (request) => {
  const {
    url
  } = request;
  if (!/https|http/.test(url)) {
    request.url = url.startsWith('/') ?
      `${BASE_URL}${url}` :
      `${BASE_URL}/${url}`;
  }
};

const handleToken = (request) => {
  const token = uni.getStorageSync(TOKEN_KEY);
  if (token) {
    request.header.Authorization = token;
  }
};

const showLoading = () => {
  uni.showLoading({
    title: '加载中',
  });
};

const hideLoading = () => {
  uni.hideLoading();
};


uni.addInterceptor('request', {
  invoke(args) {
    // if (args.loading) {
    //   loadingTimer = setTimeout(showLoading, LOADING_DELAY);
    // }
    showLoading()
    handleURL(args);
  },
  success(args) {
    // 请求成功后，修改code值为1
  },
  fail(err) {

  },
  complete(res) {
    clearTimeout(loadingTimer);
    hideLoading();
  },
})


const wrapRequest = ({
  url = '',
  data = {},
  method = 'GET',
  header = {},
  loading = true,
} = {}) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...defaultOptions,
      url,
      data,
      method,
      loading,
      header: {
        ...defaultOptions.header,
        ...header,
      },
      success: (res) => {
        resolve(res)
      },
      fail: (res) => {
        reject(res)
      },
      complete: () => {}
    });
  })

};

export const get = (params) =>
  wrapRequest({
    ...params,
    method: 'GET'
  });

export const post = (params) =>
  wrapRequest({
    ...params,
    method: 'POST'
  });
export const put = (params) =>
  wrapRequest({
    ...params,
    method: 'PUT'
  });
export const del = (params) =>
  wrapRequest({
    ...params,
    method: 'DELETE'
  });

export const testGet = function(params) {
  console.log('ok');
  // var _uni = params
  uni.request({
    url: 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata', //仅为示例，并非真实接口地址。
    success: (res) => {
      console.log(res.data);

    }
  });
}